package com.self.cloudmall.ums.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.self.cloudmall.common.constant.PmsConstant;
import com.self.cloudmall.common.dto.LoginUserDto;
import com.self.cloudmall.common.dto.SocialLoginDto;
import com.self.cloudmall.common.enumm.ResultErrorEum;
import com.self.cloudmall.common.utils.HttpUtil;
import com.self.cloudmall.common.utils.R;
import com.self.cloudmall.ums.client.OrderClient;
import com.self.cloudmall.ums.entity.MemberLevelEntity;
import com.self.cloudmall.ums.service.MemberLevelService;
import com.self.cloudmall.ums.vo.LoginMemberVo;
import com.self.cloudmall.ums.vo.MemberRegVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.cloudmall.ums.utils.PageUtils;
import com.self.cloudmall.ums.utils.Query;

import com.self.cloudmall.ums.mapper.MemberMapper;
import com.self.cloudmall.ums.entity.MemberEntity;
import com.self.cloudmall.ums.service.MemberService;
import org.springframework.util.CollectionUtils;


@Slf4j
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberMapper, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Autowired
    private OrderClient orderClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R regist(MemberRegVo memberRegVo) {
        R res = checkUnique(memberRegVo);
        if (!res.isSuccess()){
            return res;
        }
        MemberEntity memberEntity = new MemberEntity();
        BeanUtils.copyProperties(memberRegVo,memberEntity);
        memberEntity.setMobile(memberRegVo.getPhone());
        //获取会员默认等级id
        List<MemberLevelEntity> list = memberLevelService.lambdaQuery()
                .eq(MemberLevelEntity::getDefaultStatus, PmsConstant.DEFAULT)
                .list();
        if (!CollectionUtils.isEmpty(list)){
            memberEntity.setLevelId(list.get(0).getId());
        }
        memberEntity.setStatus(PmsConstant.ENABLE);
        memberEntity.setCreateTime(new Date());
        memberEntity.setNickname(memberRegVo.getUsername());
        //密码加密，md5+salt
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberEntity.getPassword());
        memberEntity.setPassword(encode);
        save(memberEntity);
        return R.ok();
    }

    @Override
    public R login(LoginMemberVo loginMemberVo) {
        List<MemberEntity> list = this.lambdaQuery().eq(MemberEntity::getUsername, loginMemberVo.getLoginAccount())
                .or().eq(MemberEntity::getMobile,loginMemberVo.getLoginAccount())
                .list();
        if (CollectionUtils.isEmpty(list)){
            return R.error("用户名或手机号不存在，请先注册");
        }
        MemberEntity memberEntity = list.get(0);
        if (memberEntity.getStatus() != null && memberEntity.getStatus() == PmsConstant.DISABLE) {
            return R.error("账户被禁用，请联系管理员");
        }
        //校验密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(loginMemberVo.getPassword(),memberEntity.getPassword())){
            return R.error("账户或密码错误");
        }
        LoginUserDto loginUserDto = new LoginUserDto();
        BeanUtils.copyProperties(memberEntity,loginUserDto);
        return R.ok().setData(loginUserDto);
    }

    @Override
    public R socialLogin(SocialLoginDto socialLoginDto) {
        //判断用户是否注册，如果已经注册，就登录成功，没注册，则注册
        MemberEntity one = this.lambdaQuery().eq(MemberEntity::getUid, socialLoginDto.getUid())
                .one();
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setAccessToken(socialLoginDto.getAccessToken());
        memberEntity.setExpiresIn(socialLoginDto.getExpiresIn());
        if (one != null && (one.getStatus() == null || PmsConstant.DISABLE == one.getStatus())){
            return R.error("用户被禁用，请联系管理员");
        }
        LoginUserDto loginUserDto = new LoginUserDto();
        if (one != null){
            memberEntity.setId(one.getId());
            this.updateById(memberEntity);
            BeanUtils.copyProperties(one,loginUserDto);
            return R.ok().setData(loginUserDto);
        }else{
            JSONObject jsonObject = null;
            try {
                StringBuilder userInfoUrl = new StringBuilder();
                userInfoUrl.append(socialLoginDto.getUserInfoUrl());
                userInfoUrl.append("?").append("access_token=").append(socialLoginDto.getAccessToken());
                userInfoUrl.append("&").append("uid=").append(socialLoginDto.getUid());
                jsonObject = HttpUtil.doGet(userInfoUrl.toString());
                if (jsonObject == null){
                    log.error("社交登录获取不到用户信息");
                }
            } catch (Exception e) {
                log.error("社交登录获取用户信息异常：{}",e);
            }
            memberEntity.setUid(socialLoginDto.getUid());
            if (jsonObject != null){
                memberEntity.setCity(jsonObject.getString("city"));
                memberEntity.setHeader(jsonObject.getString("profile_image_url"));
                memberEntity.setGender("m".equalsIgnoreCase(jsonObject.getString("gender"))?1:0);
                memberEntity.setNickname(jsonObject.getString("screen_name"));
            }
            //获取会员默认等级id
            List<MemberLevelEntity> list = memberLevelService.lambdaQuery()
                    .eq(MemberLevelEntity::getDefaultStatus, PmsConstant.DEFAULT)
                    .list();
            if (!CollectionUtils.isEmpty(list)){
                memberEntity.setLevelId(list.get(0).getId());
            }
            memberEntity.setStatus(PmsConstant.ENABLE);
            memberEntity.setCreateTime(new Date());
            this.save(memberEntity);
            BeanUtils.copyProperties(memberEntity,loginUserDto);
            return R.ok().setData(loginUserDto);
        }
    }

    @Override
    public R orderList(Map<String, Object> params) {
        return orderClient.orderList(params);
    }

    private R checkUnique(MemberRegVo memberRegVo) {
        List<MemberEntity> list = this.lambdaQuery().eq(MemberEntity::getUsername, memberRegVo.getUsername())
                .eq(MemberEntity::getStatus, PmsConstant.ENABLE)
                .list();
        List<MemberEntity> phoneList = this.lambdaQuery().eq(MemberEntity::getMobile, memberRegVo.getPhone())
                .eq(MemberEntity::getStatus, PmsConstant.ENABLE)
                .list();
        if (!CollectionUtils.isEmpty(list)){
            return R.error(ResultErrorEum.USERNAME_REPEAT.getCode(),ResultErrorEum.USERNAME_REPEAT.getMessage());
        }
        if (!CollectionUtils.isEmpty(phoneList)){
            return R.error(ResultErrorEum.MOBILE_REPEAT.getCode(),ResultErrorEum.MOBILE_REPEAT.getMessage());
        }
        return R.ok();
    }


}